﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class OldApplyRootMotion : MonoBehaviour
{
    //-- Root Motion 控制变量
    Transform m_rootBone;
    Vector3 m_lastRootPos;
    Vector3 m_rootMotion;
    int m_lastAnimTime;
    public List<string> m_AnimNameList;
    Animation anim;

    void Start()
    {
        //-- 从SkinnedMeshRenderer中读取Root Bone
        SkinnedMeshRenderer skinMesh = this.gameObject.GetComponentInChildren<SkinnedMeshRenderer>();
        m_rootBone = skinMesh.rootBone;

        //-- 变量初始化
        m_rootMotion = Vector3.zero;
        m_lastRootPos = m_rootBone.localPosition;
        m_lastAnimTime = 0;

        anim = this.GetComponent<Animation>();
    }

    void Update()
    {
        //-- Apply Root Motion
        Vector3 nextPos = this.transform.position + m_rootMotion;
        this.transform.position = nextPos;

        //-- 测试代码：更新摄像机
        Camera.main.transform.LookAt(this.transform);
    }

    void LateUpdate()
    {
        for (int i = 0; i < m_AnimNameList.Count; i++)
        {
            string animName = m_AnimNameList[i];
            AnimationState animState = anim[animName];

            if (anim.IsPlaying(animName))
            {
                if ((int)animState.normalizedTime > m_lastAnimTime)
                {
                    //-- 动画循环处理
                    m_lastRootPos = m_rootBone.localPosition;
                    m_rootMotion = Vector3.zero;
                }
                else
                {
                    //-- 计算当前帧的Root Motion
                    Vector3 rootPos = m_rootBone.localPosition;
                    m_rootMotion = rootPos - m_lastRootPos;
                    m_lastRootPos = rootPos;
                    rootPos.x = 0;
                    rootPos.z = 0;
                    m_rootMotion.y = 0;
                    m_rootBone.localPosition = rootPos;
                }
                m_lastAnimTime = (int)animState.normalizedTime;

                return;
            }

        }

        


    }
}
